package com.news.cloud.jpa.repository;

import com.news.cloud.jpa.domain.Channel;
import com.news.cloud.jpa.domain.Feed;
import com.news.cloud.jpa.domain.Provider;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by hiephn on 2014/08/28.
 */
public interface FeedRepository extends JpaRepository<Feed, Integer> {

    Feed findOneByNameAndChannelAndProvider(String name, Channel channel, Provider provider);

    Feed findOneByProviderFeedIdAndProviderId(String providerFeedId, int providerId);

    Page<Feed> findByChannelIn(List<Channel> channels, Pageable pageable);

    Page<Feed> findByChannelNotInOrderByHotDesc(List<Channel> channels, Pageable pageable);

    List<Feed> findByIdIn(List<Integer> feedIds);

    @Query(value = "select feed_id from feed_read fr where fr.user_id = ?1 and fr.feed_id in ?2", nativeQuery = true)
    List<Integer> findReadIds(int userId, List<Integer> feedIds);

    @Modifying
    @Query(value = "delete from first_page fp where fp.provider_id = ?1", nativeQuery = true)
    void resetFirstPageFeed(int providerId);

    @Modifying
    @Query(value = "insert into first_page (provider_id, feed_id, pub_date) values (?1, ?2, ?3)", nativeQuery = true)
    void saveFirstPageFeed(int providerId, int feedId, Timestamp pubDate);

//    @Query(value = "select feed_id from first_page fp where fp.feed_id in ?1", nativeQuery = true)
//    List<Integer> findFirstPageIdsByFeedIds(List<Integer> feedIds);

    @Query(value = "select feed_id from first_page fp order by fp.pub_date limit ?1 offset ?2", nativeQuery = true)
    List<Integer> findFirstPageIdsOrderByPubDateDesc(int limit, int offset);
}
